package util::Daemon;

use strict;
use warnings;

#use FindBin;

#my $path = "$FindBin::Bin/../";
use POSIX;


sub new
{
    my $class = shift;
    my $parm = shift;
    my $self = {};
    $self->{'work_dir'} = $parm->{'work_dir'} || '/';
    $self->{'PID'} = $parm->{'pid_file'} || '/dev/null';
    $self->{'child_STDOUT'} = $parm->{'runlog'} || '/dev/null';
    $self->{'child_STDERR'} = $parm->{'error_log'} || '/dev/null';
    bless $self, $class;
    return $self;
}

sub _daemon
{
    my $self = shift;
    chdir $self->{'work_dir'} if $self->{'work_dir'};
    
    my $child = fork;
    die "Can't fork: $!" unless defined($child);
    exit(0) if $child; # parent dies;
    POSIX::setsid(); # become session leader
    open(STDIN,"</dev/null");
    open ( STDOUT, ( $self->{child_STDOUT} ? "+>$self->{child_STDOUT}" : "+>/dev/null"    ) );
    open ( STDERR, ( $self->{child_STDERR} ? "+>$self->{child_STDERR}" : "+>/dev/null"    ) );
    umask(0); # forget file mode creation mask
    $ENV{PATH} = '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin';
    delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
    
    $self->_pid($$);
}

sub _pid
{

    my $self = shift;
    my $pid = shift;
#	$self->{'PID'} = $path . $pid;
    open my $fh_pid, ">", "$self->{PID}" or die "$!\n";
    print $fh_pid $pid;
    close $fh_pid;
}

sub _checkpid
{
    my $self = shift;

    if ( -f $self->{'PID'} )
    {
        open my $fh_pid, "<" , "$self->{PID}" or warn "$!\n";
        my $line = readline $fh_pid;
        chomp $line;
        my $proc = "/proc/" . "$line";
        if ( -d $proc )
        {
            return 1;
        }
        else
        {
            unlink $self->{'PID'};
            return 0;
        }
    }
    else
    {
        return 0;
    }
}

sub Kill_Daemon
{
    my $self = shift;
	chdir $self->{'work_dir'} if $self->{'work_dir'};
    if ( -f $self->{'PID'} )
    {
        open my $fh_pid, "<" , "$self->{PID}" or warn "$!\n";
        my $line = readline $fh_pid;
        chomp $line;
        kill 9, $line;
        unlink $self->{'PID'};
    }
    else
    {
        print "cann't find pid file $self->{'PID'}\n";
    }
}

1;
